﻿using IPlugin;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Plugin
{
    public class Plugin : IPlugin.IPlugin
    {
        private string htmlFileName = "index.html";
        private StringBuilder stringBuilder;
        private Datenbankmanager dbm;
        public string Name
        {
            get { return "url"; }
        }
        public string Version
        {
            get { return "1.0 Beta"; }
        }

        public Plugin()
        {
            dbm = new Datenbankmanager();

            if (!File.Exists("Plugins\\" + Name + '\\' + htmlFileName))
            {
                Console.WriteLine("Error: URL-Plugin\n" +
                    "Im Verzeichnis 'Plugins\\" + Name + "' wurde keine HTML-Datei gefunden.\n" +
                "Bitte stellen sie eine HTML-Datei mit dem Dateinamen '" + htmlFileName + "' bereit.\nServer muss beendet werden.");
                Console.Read();
                Environment.Exit(0);
            }

            FileStream fs = null;
            StreamReader sr = null;
            try
            {
                fs = File.OpenRead("Plugins\\" + Name + '\\' + htmlFileName);
                sr = new StreamReader(fs);
                stringBuilder = new StringBuilder("");
                while (!sr.EndOfStream)
                {
                    stringBuilder.Append(sr.ReadLine());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: Filebrowser-Plugin\nDetail: " + ex.Message);
                Console.Read();
                Environment.Exit(0);
            }
            finally
            {
                if (fs != null)
                    fs.Close();
                if (sr != null)
                    sr.Close();
            }
        }
        public Response ExecutePlugin(Request req)
        {
            string decodedPath = HttpUtility.UrlDecode(req.ReqUrl.Path); //z.B. %20 umwandeln zu ' '
            if (!decodedPath.Equals("/"))
                decodedPath = decodedPath.TrimEnd('/');
            string[] separatedBlocks = decodedPath.Split('/');

            string htmlOutput = stringBuilder.ToString();
            Response resp = new Response(req.getSocket());

            if (req.ReqPostVars != null && req.ReqPostVars.ParameterList != null)
            {
                if (req.ReqPostVars.ParameterList.ContainsKey("urlInputField"))
                {
                    string url = req.ReqPostVars.ParameterList["urlInputField"];
                    if (!string.IsNullOrWhiteSpace(url))
                    {
                        string keyForUrl = dbm.insertNewEntry(url);
                        if (keyForUrl != null)
                        {
                            string host = req.Header["Host"];
                            if (host == null)
                                host = "";
                            htmlOutput = htmlOutput.Replace("{Embedded-Sensor-Cloud-Content}", "<p>Short-Url:<br/>" + host + "/" + this.Name + "/" + keyForUrl + "</p>");
                            resp.StatusCode = 200;
                            resp.StatusText = "OK";
                            resp.ContentType = "text/html";
                            resp.Data = htmlOutput;
                            return resp;
                        }
                        else
                        {
                            //DB-Error
                            htmlOutput = "<p>Aus technischen Gr&uuml;nden kann derzeit keine URL generiert werden.</p>";
                            resp.StatusCode = 200;
                            resp.StatusText = "OK";
                            resp.ContentType = "text/html";
                            resp.Data = htmlOutput;
                            return resp;
                        }
                    }
                }
            }
            else if (separatedBlocks.Length == 3)
            {
                //Zeichen nach ../url/ wurden eingegeben
                string shortKey = separatedBlocks[2];
                if (!string.IsNullOrWhiteSpace(shortKey))
                {
                    string url = dbm.getUrlByKey(shortKey);
                    if (url != null)
                    {
                        resp.StatusCode = 301;
                        resp.StatusText = "Moved Permanently\nLocation: http://" + url;
                        resp.ContentType = "text/html";
                        resp.Data = "";
                        return resp;
                    }
                }
            }


            htmlOutput = htmlOutput.Replace("{Embedded-Sensor-Cloud-Content}", "<p>Geben Sie Ihre Url in das Textfeld ein und klicken Sie auf generieren, um eine Short-Url zu erstellen.</p>");

            resp.StatusCode = 200;
            resp.StatusText = "OK";
            resp.ContentType = "text/html";
            resp.Data = htmlOutput;
            return resp;
        }
    }
}
